package com.guo.anim.particle;

import android.graphics.Bitmap;
import android.graphics.Color;

/**
 * 从Bitmap中提取主题色
 */
public class BitmapColorUtil {
    //设置采样点个数为8
    private static final int MAX_SAMPLE_POINTS = 8;

    /**
     * 从图片中提取背景特征色，以原图作为素材，从4个点采样取平均值
     * @param bitmap
     * @return
     */
    public static int extractColor(Bitmap bitmap){
        int r = 0;
        int g = 0;
        int b = 0;
        int delta = Math.min(bitmap.getWidth(), bitmap.getHeight()) / 10;
        int countPerLine = MAX_SAMPLE_POINTS / 4;
        for(int i = 0; i < countPerLine; i++){
            int positionTopX = (i + 1)  * bitmap.getWidth() / (countPerLine + 1);
            int positionRightY = (i + 1)  * bitmap.getHeight() / (countPerLine + 1);
            int topColor = bitmap.getPixel(positionTopX, delta);
            int bottomColor = bitmap.getPixel(positionTopX, bitmap.getHeight() - delta);
            int rightColor = bitmap.getPixel(bitmap.getWidth() - delta, positionRightY);
            int leftColor = bitmap.getPixel(delta, positionRightY);
            r += (Color.red(topColor) + Color.red(bottomColor) + Color.red(rightColor) + Color.red(leftColor));
            g += (Color.green(topColor) + Color.green(bottomColor) + Color.green(rightColor) + Color.green(leftColor));
            b += (Color.blue(topColor) + Color.blue(bottomColor) + Color.blue(rightColor) + Color.blue(leftColor));
        }
        r /= (4 * countPerLine);
        g /= (4 * countPerLine);
        b /= (4 * countPerLine);
        return Color.rgb(r, g, b);
    }
}
